#include "qAnalitikaKomintentiwidget.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDesktopWidget>
#include "chelperclass.h"

QAnalitikaKomintentiWidget::QAnalitikaKomintentiWidget(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,m_selectedText("") 
    ,m_selectedTextName("")
	,m_offset(0)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.prevButton, SIGNAL(clicked()), this, SLOT(prevButtonPressed()));
	connect(ui.nextButton, SIGNAL(clicked()), this, SLOT(nextButtonPressed()));

	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
    lista("%");
	lista_detail("-1");
}


QAnalitikaKomintentiWidget::~QAnalitikaKomintentiWidget()
{

}


void QAnalitikaKomintentiWidget::pressEscape()
{
    emit closeW();
}

void QAnalitikaKomintentiWidget::prevButtonPressed()
{
	m_offset = m_offset <= 50 ? 0 : m_offset - 50;
	lista("%%%");
}

void QAnalitikaKomintentiWidget::nextButtonPressed()
{
	m_offset += 50;
	lista("%%%");
}

void QAnalitikaKomintentiWidget::lista(const QString& nameSearch)
{
    QLocale loc;
    int r = 0;
    int c = 2;
    int fieldNo[2];
    QString country[2];
    
    bool isNumeric = false;

    int colWidth[] = {50, 650};
    QString colName[7] = {"id", "artikal", "edm", "proizvoditel", "sum(vkol)", "sum(ikol)", "sum(vkol)-sum(ikol)"};
    QString temp = "";
    temp = 
        " SELECT komintent_id, naziv "
        " FROM dokumenti "
        " LEFT JOIN komintenti ON dokumenti.komintent_id = komintenti.id "
        " GROUP BY komintent_id, naziv "
        " HAVING komintenti.naziv LIKE '%" + nameSearch + "%' limit 50 OFFSET "+ QString::number(m_offset, 10);

	QSqlQuery query(temp);
    QSqlError err = query.lastError();
    model = new QStandardItemModel(r, c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Коминтент"));
    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);

    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
	CHelperClass chc(this);
	float vkVlezKol = 0.f;
	float vkIzlezKol = 0.f;
	float vkSaldo = 0.f;
	setUpdatesEnabled(false);
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QString temp = query.value(i).toString();
            QStandardItem *item = NULL; 
            item = new QStandardItem(temp);
            item->setTextAlignment(Qt::AlignLeft);
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
		row++;
    } 
	setUpdatesEnabled(true);

    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
    this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
}

void QAnalitikaKomintentiWidget::lista_detail(const QString& nameSearch)
{
	QLocale loc;
	if (nameSearch.length() < 0)
	{
		ui.tableView_2->hide();
		return;
	}

	int r = 0;
	int c = 7;
	int fieldNo[7];
	QString country[11];
	int colWidth[] = {50, 180, 120, 200, 80, 80, 80};
	QString colName[] = {"dok_id", "dok_tip", "datum", "artikal", "ikol", "icena", "rabat"};
    QString temp = "";

    temp = 
	" SELECT dokumenti.dok_id, dokumenti.dok_tip, datum, artikal, ikol, icena, rabat "
	" FROM dokumenti "
	" LEFT JOIN magacin ON dokumenti.dok_id = magacin.dok_id AND "
	" dokumenti.dok_tip_link = magacin.dok_tip_link "
	" LEFT JOIN artikli ON magacin.artikal_id = artikli.id "
	" WHERE komintent_id = " + m_selectedText + 
	" ORDER BY datum, dokumenti.id";

    QSqlQuery query(temp);

	model2 = new QStandardItemModel(r,c);
	model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Док.Ид."));
	model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Вид на документ"));
	model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Датум"));
	model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Артикал"));
	model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Кол."));
	model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Цена"));
	model2->setHeaderData( 6, Qt::Horizontal, trUtf8("Рабат"));
	ui.tableView_2->setModel(model2);
	header2 = new QHeaderView(Qt::Horizontal, this);
	header2->setClickable(true);
	ui.tableView_2->setHorizontalHeader(header2);
	header2->show();
	int row = 0;
	float sumaDDV = 0.f;

    while (query.next()) 
	{
		for (int i = 0; i < c; i++)
		{
			
			QStandardItem *item = NULL;
			QString temp2 = query.value(i).toString();
			if (i == 1)
			{
				temp = query.value(0).toString(); 
				int tipTemp = temp2.toInt();
				switch(tipTemp)
				{
				case 20 : temp2 = trUtf8("ПРИЕМ. - ") + temp; break;
				case 22 : temp2 = trUtf8("НАЛОГ  - ") + temp; break;
				case 23 : temp2 = trUtf8("ПОВР.  - ") + temp; break;
				case 24 : temp2 = trUtf8("ПРИЕМ. - ") + temp; break;
				case 40 : temp2 = trUtf8("ИСПРА. - ") + temp; break;
				case 41 : temp2 = trUtf8("НАЛОГ  - ") + temp; break;
				case 44 : temp2 = trUtf8("ИСПРА. - ") + temp; break;
				case 80 : temp2 = trUtf8("НАРАЧ. - ") + temp; break;
				case 18 : temp2 = trUtf8("НАРАЧ. - ") + temp; break;
				}
				item = new QStandardItem(temp2);
				item->setTextAlignment(Qt::AlignLeft);
			}
			else if (i > 3)
			{
				item = new QStandardItem(loc.toString(temp2.toFloat(), 'f', 2));
				item->setTextAlignment(Qt::AlignRight);
			}
			else 
			{
				item = new QStandardItem(temp2);
				item->setTextAlignment(Qt::AlignLeft);
			}

			item->setEditable(false);
			ui.tableView_2->setRowHeight(row, 18);
			ui.tableView_2->setColumnWidth(i, colWidth[i]);
			model2->setItem(row, i, item);
		}
		row++;
    }
	ui.tableView_2->show();
}
void QAnalitikaKomintentiWidget::on_lineEdit_textChanged(const QString &)
{
	lista(ui.lineEdit->text());
}


void QAnalitikaKomintentiWidget::on_tableView_clicked(const QModelIndex &modelX)
{
	int i = modelX.row();
	m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
}

void QAnalitikaKomintentiWidget::setFocusSearchField()
{
	ui.lineEdit->setFocus();
}


void QAnalitikaKomintentiWidget::pressReturn()
{
    if (ui.lineEdit->hasFocus())
    {
        ui.tableView->setFocus();
    }
    else if (ui.tableView->hasFocus())
	{
		emit sAnalitikaKomintentiToDokument(m_selectedText, m_selectedTextName, m_selectedTextNameSaldo);	
	}

}

void QAnalitikaKomintentiWidget::setInitText(QString text)
{
	ui.lineEdit->setText(text);
	ui.lineEdit->selectAll();
	ui.lineEdit->setFocus();
}

void QAnalitikaKomintentiWidget::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
    m_selectedTextName = model->item(i, 1) ? model->item(i, 1)->text():"";
    m_selectedTextNameSaldo = model->item(i, 5) ? model->item(i, 5)->text():"";
	lista_detail(m_selectedText);
}

void QAnalitikaKomintentiWidget::radioButtonClicked()
{
    lista(ui.lineEdit->text());
}